package com.gxa.ssm340.controller;


import com.gxa.ssm340.entity.dto.CpnUsedPageDTO;
import com.gxa.ssm340.entity.vo.CpnUsedListVO;
import com.gxa.ssm340.entity.vo.CpnUsedVO;
import com.gxa.ssm340.exception.BizException;
import com.gxa.ssm340.service.UserCancelService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 导出控制器
 */
@RestController
@RequestMapping("/user")
public class ExportCpnController {
    @Autowired
    private UserCancelService userCancelService;

    @GetMapping("/exportCpnUsedList")
    public void exportData(HttpServletResponse response) throws IOException, BizException {
        // 创建一个工作簿对象
        Workbook workbook = new XSSFWorkbook();
        CpnUsedPageDTO cpnUsedPageDTO = new CpnUsedPageDTO();
        cpnUsedPageDTO.setPage(0);
        cpnUsedPageDTO.setLimit(100);
        List<CpnUsedListVO> cpnUsedListVOS = userCancelService.selectByTime(cpnUsedPageDTO);
        System.out.println(cpnUsedListVOS);
        // 创建一个工作表对象
        Sheet sheet = workbook.createSheet("Data");
        // 创建行和单元格，并将数据写入单元格中
        int rowIndex = 0;
        for (CpnUsedListVO item : cpnUsedListVOS) {
            Row row = sheet.createRow(rowIndex++);
            int cellIndex = 0;
            row.createCell(cellIndex++).setCellValue(item.getId());
            for (CpnUsedVO cpnUsedVO : item.getCpnUsedVO()) {
                row.createCell(cellIndex++).setCellValue(cpnUsedVO.getUserId());
                row.createCell(cellIndex++).setCellValue(cpnUsedVO.getUserName());
                row.createCell(cellIndex++).setCellValue(cpnUsedVO.getGetUseTime());
                row.createCell(cellIndex++).setCellValue(cpnUsedVO.getPhone());
                row.createCell(cellIndex++).setCellValue(cpnUsedVO.getCouponName());
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
// 自动调整所有列的单元格大小
        for (int i = 0; i < cpnUsedListVOS.get(0).getClass().getDeclaredFields().length; i++) {
            sheet.autoSizeColumn(i);
        }
        // 设置响应头信息，告诉浏览器响应的是一个Excel文件
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=\"Coupon.xlsx\"");
        // 将Excel文件写入响应输出流中，返回给前端
        workbook.write(response.getOutputStream());
    }
}

